﻿using B.MESUI.Login.WareHouseManage.Dtos;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace B.MESUI.Login.WareHouseManage.LocationTest
{
    public partial class UpdateWareHouseLocationForm : DevExpress.XtraEditors.XtraForm
    {
        public delegate void LocationLoadDelegate();
        public event LocationLoadDelegate LocationLoad;
        private string _currentId;
        public UpdateWareHouseLocationForm(string id)
        {
            InitializeComponent();
            _currentId = id;
        }
        public async Task LoadWarehousesAsync()
        {
            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.GetAsync("http://39.103.49.30:9981/api/Area/GetWarehouseAreaIdAndName");

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResultStandard<AreaIdAndName>>(json);

                        // 绑定数据到 GridLookUpEdit
                        gridLookUpEdit1.Properties.DataSource = result.ResultData;
                        gridLookUpEdit1.Properties.ValueMember = "id";
                        gridLookUpEdit1.Properties.DisplayMember = "areaname";

                        // 配置视图 - 这是关键修复点！
                        // 获取或创建 GridView
                        GridView view = gridLookUpEdit1.Properties.View as GridView;
                        if (view == null)
                        {
                            view = new GridView();
                            gridLookUpEdit1.Properties.View = view;
                        }

                        // 清除现有列
                        view.Columns.Clear();

                        // 添加列：仓库名称
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "areaname",
                            Caption = "库区名称",
                            Visible = true
                        });

                        // 添加列：仓库ID（可选）
                        view.Columns.Add(new GridColumn()
                        {
                            FieldName = "id",
                            Caption = "库区ID",
                            Visible = false // 隐藏ID列
                        });

                        // 设置最佳列宽
                        view.BestFitColumns();

                        // 默认选中第一个
                        if (result.ResultData.Count > 0)
                            gridLookUpEdit1.EditValue = null;
                    }
                    else
                    {
                        MessageBox.Show("无法加载库区信息");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }

        private async void UpdateWareHouseLocationForm_Load(object sender, EventArgs e)
        {
            await LoadWarehousesAsync();
            using (var client = new HttpClient())
            {
                try
                {
                    string url = $"http://39.103.49.30:9981/api/Location/GetLOCATIONDESC?id={_currentId}";
                    var response = await client.GetAsync(url);

                    if (response.IsSuccessStatusCode)
                    {
                        string json = await response.Content.ReadAsStringAsync();
                        var result = JsonConvert.DeserializeObject<ApiResultStandardForEntity<LocationModel>>(json);

                        // 回显数据到控件
                        textEdit1.Text = result.ResultData.locationid;
                        textEdit2.Text = result.ResultData.locationname;
                        gridLookUpEdit1.EditValue = result.ResultData.areaid;
                        textEdit3.Text = result.ResultData.locationdesc;
                    }
                    else
                    {
                        MessageBox.Show("无法加载区域详细信息");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }

        private async void simpleButton1_Click(object sender, EventArgs e)
        {
            string locationCode = textEdit1.Text.Trim();
            string locationName = textEdit2.Text.Trim();
            string warehouseAreaId = gridLookUpEdit1.EditValue?.ToString();
            string remark = textEdit3.Text.Trim();

            // 非空校验...

            var model = new LocationModel
            {
                id = _currentId,
                locationid = locationCode,
                locationname = locationName,
                areaid = warehouseAreaId,
                locationdesc = remark
            };

            string jsonContent = JsonConvert.SerializeObject(model);
            var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");

            using (var client = new HttpClient())
            {
                try
                {
                    var response = await client.PostAsync("http://39.103.49.30:9981/api/Location/UpdateLOCATIONMODEL", content);

                    if (response.IsSuccessStatusCode)
                    {
                        MessageBox.Show("更新成功！");
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                        LocationLoad.Invoke();
                    }
                    else
                    {
                        string errorText = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"更新失败: {errorText}");
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show($"发生错误: {ex.Message}");
                }
            }
        }
    }
}